package com.getpebble.android.notifications.model;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Notification;
import android.app.PendingIntent;
import android.content.SharedPreferences;
import android.os.Build.VERSION;
import android.os.Bundle;
import android.service.notification.StatusBarNotification;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationCompat.Action;
import android.support.v4.app.NotificationCompat.WearableExtender;
import android.support.v4.app.RemoteInput;
import android.text.TextUtils;
import com.getpebble.android.PebbleApplication;
import com.getpebble.android.R;
import com.getpebble.android.common.core.trace.Trace;
import com.getpebble.android.common.core.util.PblPreferences;
import com.getpebble.android.common.model.PblAndroidAppModel;
import com.getpebble.android.common.model.PblAndroidAppModel.Record;
import com.getpebble.android.framework.notification.gmail.GmailCheckerService;
import com.getpebble.android.framework.notification.gmail.GmailCheckerService.GmailAction;
import com.getpebble.android.framework.receiver.SMSReceiver.SmsNotification;
import com.getpebble.android.notifications.model.Actions.NotificationDismissKey;
import com.getpebble.android.notifications.model.Actions.PblNotificationAction;
import com.getpebble.android.notifications.model.Actions.PblNotificationAndroidAction;
import com.getpebble.android.notifications.model.Actions.PblNotificationDismissAction;
import com.getpebble.android.notifications.model.Actions.PblNotificationGmailAction;
import com.getpebble.android.notifications.model.Actions.PblNotificationOpenOnPhoneAction;
import com.getpebble.android.notifications.model.Actions.PblNotificationReplyAction;
import com.getpebble.android.notifications.model.Actions.PblNotificationSMSReplyAction;
import com.getpebble.android.notifications.model.apps.NotificationExtractor;
import com.getpebble.android.notifications.model.apps.NotificationExtractor.DuplicateNotificationException;
import com.google.common.base.Predicates;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.sun.mail.smtp.SMTPMessage;
import java.util.ArrayList;
import java.util.List;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;

public class PblNotification {
    public static final long DEFAULT_REMOVED_NOTIFICATION_CHECKED_FOR_X_MILLIS = TimeUnit.SECONDS.toMillis(15);
    public static final long GMAIL_NOTIFICATION_CHECKED_FOR_X_MILLIS = TimeUnit.MINUTES.toMillis(60);
    public static final long HANGOUTS_NOTIFICATION_CHECKED_FOR_X_MILLIS = TimeUnit.MINUTES.toMillis(1);
    private static final String TAG = PblNotification.class.getSimpleName();
    private final List<PblNotificationAction> mActions;
    private final int mAndroidNotificationId;
    private final String mAndroidNotificationKey;
    private final String mAndroidNotificationTag;
    private final Record mAppRecord;
    private final String mApplicationName;
    private final String mGroupKey;
    private final boolean mIsClearable;
    private boolean mIsDuplicate;
    private final boolean mIsGroupSummary;
    private final boolean mIsOnGoing;
    private final String mLastTextLine;
    private final LegacyNotification mLegacyContent;
    private final Notification mNotification;
    private NotificationContent mNotificationContent;
    private final String mPackageName;
    private final long mPostTimeUtcMillis = System.currentTimeMillis();
    private final Source mSource;
    private final String mTickerText;
    private int notificationActionId = 0;

    public static class LegacyNotification {
        public String body;
        public String subtitle;
        public String title;
    }

    public static class NotificationContent {
        public String notificationBody;
        public String notificationSummary;
        public String notificationTitle;
        public String rawNotificationBody;
    }

    public enum Source {
        ACCESSIBILITY,
        NOTIFICATION,
        SIDECHANNEL,
        DEMO,
        SMS,
        GMAIL,
        PEBBLEKIT,
        CALENDAR,
        JSKIT
    }

    @TargetApi(18)
    @SuppressLint({"NewApi"})
    public static PblNotification from(StatusBarNotification notification, Source source) throws IllegalArgumentException {
        if (notification == null) {
            throw new IllegalArgumentException("'notification' cannot be null!");
        }
        String key = null;
        if (VERSION.SDK_INT >= 20) {
            key = notification.getKey();
        }
        return new PblNotification(notification.getPackageName(), notification.getId(), notification.getTag(), key, notification.getNotification(), source, null);
    }

    public static PblNotification from(Notification notification, String packageName, Source source) throws IllegalArgumentException {
        if (notification == null) {
            throw new IllegalArgumentException("'notification' cannot be null!");
        } else if (packageName != null) {
            return new PblNotification(packageName, -1, null, null, notification, source, null);
        } else {
            throw new IllegalArgumentException("'packageName' cannot be null!");
        }
    }

    public static PblNotification from(LegacyNotification content, Source source) {
        if (content == null) {
            throw new IllegalArgumentException("'content' cannot be null!");
        } else if (source != null) {
            return new PblNotification(null, -1, null, null, null, source, content);
        } else {
            throw new IllegalArgumentException("'source' cannot be null!");
        }
    }

    public static String generateNotificationKey(String pkg, int androidId, String tag) {
        return pkg + "|" + androidId + "|" + tag;
    }

    private PblNotification(String packageName, int androidNotificationId, String androidNotificationTag, String androidNotificationKey, Notification notification, Source source, LegacyNotification legacyContent) {
        this.mPackageName = packageName;
        this.mAppRecord = PblAndroidAppModel.getAppRecord(this.mPackageName, PebbleApplication.getAppContext().getContentResolver());
        if (this.mAppRecord == null) {
            this.mApplicationName = "";
        } else {
            this.mApplicationName = this.mAppRecord.appName;
        }
        if (notification == null) {
            this.mIsOnGoing = false;
            this.mIsClearable = false;
        } else {
            this.mIsOnGoing = (notification.flags & 2) != 0;
            if (VERSION.SDK_INT < 18) {
                this.mIsClearable = false;
            } else {
                boolean z = !this.mIsOnGoing && (notification.flags & 32) == 0;
                this.mIsClearable = z;
            }
        }
        this.mAndroidNotificationId = androidNotificationId;
        this.mAndroidNotificationTag = androidNotificationTag;
        if (androidNotificationKey != null) {
            this.mAndroidNotificationKey = androidNotificationKey;
        } else {
            this.mAndroidNotificationKey = generateNotificationKey(this.mPackageName, this.mAndroidNotificationId, this.mAndroidNotificationTag);
        }
        this.mNotification = notification;
        this.mSource = source;
        this.mLegacyContent = legacyContent;
        if (this.mNotification == null) {
            this.mGroupKey = null;
            this.mIsGroupSummary = false;
            this.mTickerText = null;
            this.mLastTextLine = null;
            this.mNotificationContent = new NotificationContent();
            if (legacyContent != null) {
                this.mNotificationContent.notificationTitle = legacyContent.title;
                this.mNotificationContent.notificationSummary = legacyContent.subtitle;
                this.mNotificationContent.notificationBody = legacyContent.body;
            }
            this.mActions = new ArrayList();
            getLegacyActions();
            return;
        }
        if (this.mNotification.tickerText != null) {
            this.mTickerText = this.mNotification.tickerText.toString();
        } else {
            this.mTickerText = null;
        }
        this.mGroupKey = NotificationCompat.getGroup(notification);
        this.mIsGroupSummary = NotificationCompat.isGroupSummary(notification);
        Bundle notificationExtras = NotificationCompat.getExtras(this.mNotification);
        CharSequence[] textLines = null;
        if (notificationExtras != null && notificationExtras.containsKey("android.textLines")) {
            textLines = notificationExtras.getCharSequenceArray("android.textLines");
        }
        if (textLines == null || textLines.length <= 0) {
            this.mLastTextLine = null;
        } else {
            this.mLastTextLine = textLines[textLines.length - 1].toString();
        }
        this.mActions = getActions(this.mNotification);
    }

    public void setDismissAction(PblNotificationDismissAction newDismissAction) {
        PblNotificationDismissAction existingDismissAction = findDismissAction();
        if (existingDismissAction != null) {
            Trace.verbose(TAG, "Replacing dismiss action for notification from summary");
            this.mActions.remove(existingDismissAction);
            this.mActions.add(newDismissAction);
            newDismissAction.setId(existingDismissAction.getId());
            return;
        }
        Trace.verbose(TAG, "Adding dismiss action for notification from summary");
        addAction(newDismissAction);
    }

    public void extractContent(String groupSummaryKey) {
        if (!isLegacyNotification()) {
            try {
                this.mNotificationContent = NotificationExtractor.extractNotificationContent(this, PebbleApplication.getAppContext(), groupSummaryKey);
            } catch (DuplicateNotificationException e) {
                this.mIsDuplicate = true;
            }
        }
    }

    private void addAction(PblNotificationAction action) {
        this.mActions.add(action);
        int i = this.notificationActionId + 1;
        this.notificationActionId = i;
        action.setId(i);
    }

    public void addActionIfNotPresent(PblNotificationAction newAction) {
        boolean foundMatch = false;
        for (PblNotificationAction action : getActions()) {
            if (action.getTitle().equals(newAction.getTitle())) {
                foundMatch = true;
            }
        }
        if (!foundMatch) {
            addAction(newAction);
        }
    }

    private List<PblNotificationAction> getActions(Notification notification) {
        List<PblNotificationAction> actions = new ArrayList();
        if (notification.contentIntent != null) {
            CharSequence string = PebbleApplication.getAppContext().getString(R.string.open_on_phone_action_title);
            PendingIntent pendingIntent = notification.contentIntent;
            int i = this.notificationActionId + 1;
            this.notificationActionId = i;
            actions.add(new PblNotificationOpenOnPhoneAction(string, pendingIntent, i));
        }
        if (isClearable()) {
            Trace.debug(TAG, "Notification is clearable by Pebble Android");
            CharSequence string2 = PebbleApplication.getAppContext().getString(R.string.dismiss_action_title);
            int i2 = this.notificationActionId + 1;
            this.notificationActionId = i2;
            actions.add(new PblNotificationDismissAction(string2, i2, NotificationDismissKey.from(this)));
        }
        List<Action> wearableActions = new WearableExtender(this.mNotification).getActions();
        if (wearableActions != null) {
            Trace.debug(TAG, String.format("Found %d wearable actions", new Object[]{Integer.valueOf(wearableActions.size())}));
            for (Action action : wearableActions) {
                RemoteInput[] remoteInputs = action.getRemoteInputs();
                boolean isActionAdded = false;
                Trace.debug(TAG, "Found valid remote inputs");
                if (remoteInputs != null) {
                    int j = 0;
                    while (j < remoteInputs.length) {
                        RemoteInput remoteInput = remoteInputs[j];
                        if (remoteInput.getAllowFreeFormInput()) {
                            Trace.debug(TAG, "Found remote input with free form input");
                            ArrayList<CharSequence> choices = new ArrayList();
                            SharedPreferences sp = PblPreferences.getSharedPreferences(PebbleApplication.getAppContext());
                            for (int i3 = 0; i3 < 5; i3++) {
                                String response = sp.getString("canned_response_" + i3, null);
                                if (!TextUtils.isEmpty(response)) {
                                    choices.add(response);
                                }
                            }
                            if (remoteInput.getChoices() != null) {
                                for (CharSequence cs : remoteInput.getChoices()) {
                                    choices.add(cs);
                                }
                            }
                            string = action.title;
                            pendingIntent = action.actionIntent;
                            i = this.notificationActionId + 1;
                            this.notificationActionId = i;
                            isActionAdded = actions.add(new PblNotificationReplyAction(remoteInput, string, pendingIntent, i, choices));
                        } else {
                            j++;
                        }
                    }
                }
                if (!isActionAdded) {
                    Trace.debug(TAG, "No remote inputs found with free form input for this action");
                    string = action.title;
                    pendingIntent = action.actionIntent;
                    i = this.notificationActionId + 1;
                    this.notificationActionId = i;
                    actions.add(new PblNotificationAndroidAction(string, pendingIntent, i));
                }
            }
        }
        if ("com.google.android.gm".equals(getPackageName())) {
            Bundle extras = NotificationCompat.getExtras(notification);
            if (extras != null) {
                String account = extras.getString("android.subText");
                if (!(account == null || GmailCheckerService.getToken(account) == null)) {
                    try {
                        GmailAction gmailAction = GmailAction.MARK_AS_READ;
                        int i4 = this.notificationActionId + 1;
                        this.notificationActionId = i4;
                        actions.add(new PblNotificationGmailAction(this, gmailAction, account, i4));
                        gmailAction = GmailAction.STAR_AND_MARK_READ;
                        i4 = this.notificationActionId + 1;
                        this.notificationActionId = i4;
                        actions.add(new PblNotificationGmailAction(this, gmailAction, account, i4));
                    } catch (IllegalArgumentException e) {
                        Trace.debug(TAG, "Error generating gmail actions", e);
                    }
                }
            }
        }
        return actions;
    }

    private void getLegacyActions() {
        if (Source.SMS.equals(getSource()) && (this.mLegacyContent instanceof SmsNotification)) {
            SmsNotification smsNotification = this.mLegacyContent;
            List list = this.mActions;
            String str = smsNotification.phoneNumber;
            int i = this.notificationActionId + 1;
            this.notificationActionId = i;
            list.add(new PblNotificationSMSReplyAction(str, i));
        }
    }

    public String toString() {
        return getPackageName() + ": " + getNotificationContent();
    }

    public long getPostTimeUtcMillis() {
        return this.mPostTimeUtcMillis;
    }

    public long getPostTimeLocalMillis() {
        return this.mPostTimeUtcMillis + ((long) TimeZone.getDefault().getOffset(System.currentTimeMillis()));
    }

    public Source getSource() {
        return this.mSource;
    }

    public String getApplicationName() {
        return this.mApplicationName;
    }

    public String getPackageName() {
        return this.mPackageName;
    }

    public String getLastTextLine() {
        return this.mLastTextLine;
    }

    public NotificationContent getNotificationContent() {
        return this.mNotificationContent;
    }

    public String getTickerText() {
        return this.mTickerText;
    }

    public int getAndroidNotificationId() {
        return this.mAndroidNotificationId;
    }

    public String getAndroidNotificationTag() {
        return this.mAndroidNotificationTag;
    }

    public String getAndroidNotificationKey() {
        return this.mAndroidNotificationKey;
    }

    public Notification getNotification() {
        return this.mNotification;
    }

    public boolean isOngoing() {
        return this.mIsOnGoing;
    }

    public boolean isDuplicate() {
        return this.mIsDuplicate;
    }

    public String getGroupKey() {
        return this.mGroupKey;
    }

    public boolean isGroupSummary() {
        return this.mIsGroupSummary;
    }

    public boolean isLegacyNotification() {
        return Source.CALENDAR.equals(this.mSource) || Source.DEMO.equals(this.mSource) || Source.GMAIL.equals(this.mSource) || Source.SMS.equals(this.mSource) || Source.JSKIT.equals(this.mSource) || Source.PEBBLEKIT.equals(this.mSource);
    }

    public Record getAppRecord() {
        return this.mAppRecord;
    }

    public boolean isClearable() {
        return this.mIsClearable;
    }

    public List<PblNotificationAction> getActions() {
        return this.mActions;
    }

    public List<PblNotificationReplyAction> getReplyActions() {
        return Lists.newArrayList(Iterables.filter(getActions(), PblNotificationReplyAction.class));
    }

    public PblNotificationOpenOnPhoneAction findOpenOnPhoneAction() {
        return (PblNotificationOpenOnPhoneAction) Iterables.find(getActions(), Predicates.instanceOf(PblNotificationOpenOnPhoneAction.class), null);
    }

    public PblNotificationDismissAction findDismissAction() {
        return (PblNotificationDismissAction) Iterables.find(getActions(), Predicates.instanceOf(PblNotificationDismissAction.class), null);
    }

    public boolean isActionable() {
        return (getActions() == null || getActions().isEmpty()) ? false : true;
    }

    public List<PblNotificationAction> getOtherActions() {
        List<PblNotificationAction> result = new ArrayList(getActions());
        result.removeAll(getReplyActions());
        result.remove(findOpenOnPhoneAction());
        result.remove(findDismissAction());
        return result;
    }

    public long getTypeRemovedThresholdMillis() {
        if (this.mPackageName == null) {
            return DEFAULT_REMOVED_NOTIFICATION_CHECKED_FOR_X_MILLIS;
        }
        String str = this.mPackageName;
        Object obj = -1;
        switch (str.hashCode()) {
            case -543674259:
                if (str.equals("com.google.android.gm")) {
                    obj = null;
                    break;
                }
                break;
            case 1515426419:
                if (str.equals("com.google.android.talk")) {
                    obj = 1;
                    break;
                }
                break;
        }
        switch (obj) {
            case R.styleable.WalletFragmentStyle_buyButtonHeight /*0*/:
                return GMAIL_NOTIFICATION_CHECKED_FOR_X_MILLIS;
            case SMTPMessage.RETURN_FULL /*1*/:
                return HANGOUTS_NOTIFICATION_CHECKED_FOR_X_MILLIS;
            default:
                return DEFAULT_REMOVED_NOTIFICATION_CHECKED_FOR_X_MILLIS;
        }
    }
}
